import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { UserEntity } from '../entities/user.entity';
import { MysqlBaseService } from './mysql-base.service';

@Injectable()
export class UserService extends MysqlBaseService<UserEntity> {
  constructor(
    @InjectRepository(UserEntity) protected repository: Repository<UserEntity>,
  ) {
    super(repository);
  }

  // 重写findAll方法实现条件查询
  async findAllPage(keyword?: string, pageNo?: number, pageSize?: number) {
    // Like 模糊查询
    const where = keyword
      ? [{ username: Like(`%${keyword}%`) }, { email: Like(`%${keyword}%`) }]
      : {};

    // 计算 skip 的值
    const skip = (pageNo - 1) * pageSize;
    //findAndCount 两个值，data total总数
    const [users, total] = await this.repository.findAndCount({
      where,
      skip,
      take: pageSize,
    });
    const pageTotal = Math.ceil(total / pageSize);
    return {
      users,
      total,
      keyword,
      pageNo,
      pageSize,
      pageTotal,
    };
  }
}
